#include <firmament.h>
#include <rtdevice.h>

#define SPI_DIR_READ  0x80
#define SPI_DIR_WRITE 0x00

struct rt_spi_message tx_msg, rx_msg;

rt_err_t qx_spi_write_reg8(rt_device_t spi_device, uint8_t reg, uint8_t val)
{
    uint8_t buffer[2];

    buffer[0] = SPI_DIR_WRITE | reg;
    buffer[1] = val;

    tx_msg.send_buf = buffer;
    tx_msg.recv_buf = RT_NULL;
    tx_msg.length = 2;
    tx_msg.next = RT_NULL;
    tx_msg.cs_take = 1;
    tx_msg.cs_release = 1;

    rt_spi_transfer_message((struct rt_spi_device*)spi_device,&tx_msg);

    return RT_EOK;
}

rt_err_t qx_spi_read_reg8(rt_device_t spi_device, rt_uint8_t reg, rt_uint8_t* buffer,rt_uint32_t length)
{
    uint8_t reg_addr;

    reg_addr = SPI_DIR_READ | reg;

    tx_msg.send_buf = &reg_addr;
    tx_msg.recv_buf = RT_NULL;
    tx_msg.length = 1;
    tx_msg.next = &rx_msg;
    tx_msg.cs_take = 1;
    tx_msg.cs_release = 0;

    rx_msg.send_buf = RT_NULL;
    rx_msg.recv_buf = buffer;
    rx_msg.length = length;
    rx_msg.next = RT_NULL;
    rx_msg.cs_take = 0;
    rx_msg.cs_release = 1;

    rt_spi_transfer_message((struct rt_spi_device*)spi_device,&tx_msg);

    return RT_EOK;
}
